package com.zzyl.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.HashMap;
import java.util.Map;

/**
 * 客户登录工具
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class WechatUtil {

    //登录url
    private static final String REQUEST_URL="https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    //获取接口调用凭据access_token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    //获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    //appId
    private String appId;
    //secret秘钥
    private String secret;

    /**
     * 获取openid
     * @param code
     * @return
     */
    public String getOpenid(String code){
        Map<String, Object> appConfig = getAppConfig();
        appConfig.put("js_code", code);
        //通过糊涂工具发送请求获取
        String result  = HttpUtil.get(REQUEST_URL, appConfig);
        JSONObject entries = JSONUtil.parseObj(result);
        if(ObjectUtil.isNotEmpty(entries.getInt("errcode"))){
            throw new RuntimeException(entries.getStr("errmsg"));
        }
        return entries.getStr("openid");
    }

    /**
     * 获取接口调用凭据access_token
     * @return
     */
    public String getToken(){
        Map<String, Object> appConfig = getAppConfig();
        String result = HttpUtil.get(TOKEN_URL, appConfig);
        JSONObject entries = JSONUtil.parseObj(result);
        if(ObjectUtil.isEmpty(entries)){
            throw new RuntimeException(entries.getStr("errmsg"));
        }
        return entries.getStr("access_token");
    }

    /**
     * 获取手机号
     * @param token
     * @param phoneCode
     * @return
     */
    public String getPhone(String token,String phoneCode){
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", phoneCode);
        String result = HttpUtil.post(PHONE_REQUEST_URL + token, JSONUtil.toJsonStr(map));
        JSONObject entries = JSONUtil.parseObj(result);
        if(!entries.get("errcode").equals(0)){
            throw new RuntimeException(entries.getStr("errmsg"));
        }
        String phoneInfo = entries.getStr("phone_info");
        JSONObject entries1 = JSONUtil.parseObj(phoneInfo);
        return entries1.getStr("phoneNumber");
    }

    /**
     * 公共属性填充
     * @return
     */
    private Map<String,Object> getAppConfig(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", appId);
        map.put("secret", secret);
        return map;
    }

}
